package test.serializable;

import java.io.Externalizable ;
import java.io.IOException ;
import java.io.ObjectInput ;
import java.io.ObjectInputStream ;
import java.io.ObjectOutput ;
import java.io.ObjectOutputStream ;

/**
 * externalizable小例子
 * 实现个性化的序列化和反序列化
 * Externalizable接口必须要实现类提供一个public的无参构造方法来初始化反序列化的对象，然后在给属性赋值
 * @author 80002165 @date 2017年3月31日 下午5:38:57
 */
public class ExternalizableDemo implements Externalizable{
    private String name ;
    private int age ;
    
    public ExternalizableDemo(){
        System.out.println("no param constructor") ;
    }
    
    
    
    public ExternalizableDemo(String name, int age) {
        System.out.println("params constructor") ;
        this.name = name ;
        this.age = age ;
    }

    /* 
     * @see java.io.Externalizable#writeExternal(java.io.ObjectOutput)
     */
    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeUTF(name);
        out.writeInt(age);
        System.out.println("writeExternal !") ;
    }

    /* 
     * @see java.io.Externalizable#readExternal(java.io.ObjectInput)
     */
    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        name = in.readUTF() ;
        age = in.readInt() ;
        System.out.println("readExternal !") ;
    }
    
    private void readObject(ObjectInputStream stream) throws ClassNotFoundException, IOException{
        stream.defaultReadObject();
        this.name = stream.readUTF() ;
        this.age = 18 ;
        System.out.println("personality read object success !") ;
    }
    
    private void writeObject(ObjectOutputStream stream) throws IOException{
        stream.defaultWriteObject(); 
        stream.writeUTF(this.name);
        System.out.println("personality write object success!") ;
    }



    @Override
    public String toString() {
        return "my name is:"+name+", and my age is:"+age ;
    }
    
    public static void main(String[] args) throws ClassNotFoundException, IOException {
        ExternalizableDemo serializableObj = new ExternalizableDemo("方书豪", 26) ;
        SerializableUtils.writeToFile(serializableObj, "externalizableDemo.ser");
        SerializableUtils.readFromFile("externalizableDemo.ser") ;
        /*
         * run:
         *  params constructor
            writeExternal !
            no param constructor
            readExternal !
            果然，没有调用自己写的writeObject、和readObject方法，使用了接口定义的方法。由用户自己来实现类的序列化和反序列化过程
         */
    }
    
}
